
package nz.ac.massey.cs.webtech.rest;

import com.mongodb.BasicDBObject;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.bson.types.ObjectId;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Several JSON related utilities.
 * @author jens dietrich
 */
public class JSONUtils {
     /**
     * Parse the request payload into a JSONObject.
     */
    public static JSONObject parseJSONPayload(HttpServletRequest request) throws IOException, JSONException {
        BufferedReader reader = request.getReader();
        JSONTokener tokener = new JSONTokener(request.getReader());
        return new JSONObject(tokener);
    }
    /**
     * Parse a string into a JSONObject.
     */
    public static JSONObject parseJSON(String json) throws IOException, JSONException {
        JSONTokener tokener = new JSONTokener(json);
        return new JSONObject(tokener);
    }

    /**
     * MongoDB uses complex id objects, while backbone expects
     * a plain id attribute. This methods applies the respective id 
     * conversion from the MongoDB to the BackBone format.
     */
    public static void convertIdToExternal(JSONObject json) throws JSONException {
        JSONObject id = json.getJSONObject("_id");
        if (id !=null) {
            String _id = id.getString("$oid");
            json.remove("_id");
            json.put("id",_id);
        }
    }
    
    /**
     * MongoDB uses complex id objects, while backbone expects
     * a plain id attribute. This methods extracts the MongoDB id
     * from an JSON object submitted by BackBone.
     */
    public static ObjectId extractInternalId(JSONObject json) throws JSONException {
        String id = json.getString("id");
        return new ObjectId(id) ;
    }
    public static BasicDBObject convertJSON2Internal (JSONObject json) throws JSONException {
        BasicDBObject doc = new BasicDBObject();
        String[] names = JSONObject.getNames(json);
        for (String name:names) {
            // ignore id - ids will have to be mapped separatly (using _id and mongodb's ObjectId)
            if (!name.equals("id")) {
                doc.append(name, json.get(name));
            }
        }
        return doc;
    }
}
